package com.yuantong.xyerp.rest.exception;

import com.alibaba.fastjson.JSON;

import com.yuantong.xyerp.core.api.enums.EnumMsgCode;
import com.yuantong.xyerp.core.api.exception.YuantongException;
import com.yuantong.xyerp.core.api.model.base.RestResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * @author czg
 *
 */
@ControllerAdvice
@Slf4j
public class ExceptionResolver {

    @ExceptionHandler(YuantongException.class)
    @ResponseBody
    public RestResponseModel<String> handlerCCWException(HttpServletRequest request, Exception ex) {

        YuantongException tempEX = (YuantongException) ex;

        EnumMsgCode resultMsgCode = tempEX.getResultMsgCode();
        String code = tempEX.getCode();
        String msg = tempEX.getMsg();
        if (code == null) {
            if (resultMsgCode == null) {
                resultMsgCode = EnumMsgCode.MSG_SYS_ERROR;
            }
            code = resultMsgCode.getCode();
            msg = resultMsgCode.getMsg();
        }
        log.error("\n path: {}\n errorCode: {}\n msg:{}", request.getServletPath(), code, msg);

        return RestResponseModel.FAIL(code, msg, ex.getMessage());
    }

    /**
     * 请求参数不合法
     *
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public RestResponseModel<String> handleBindException(BindException e) {
        FieldError error = e.getFieldError();

        String msg = "请求参数不合法，请检查参数";
        if (error != null) {
            msg = error.getDefaultMessage();
        }
        return RestResponseModel.FAIL(EnumMsgCode.MSG_INVALID_PARAMS, msg);
    }


    // @ExceptionHandler(HttpMessageNotReadableException.class)
    // @ResponseBody
    // public RestResponseModel<String> handlerHttpMessageNotReadableException(HttpServletRequest request, Exception ex) {
    //     log.error("\npath : {}\n", request.getServletPath(), ex);
    //     return RestResponseModel.FAIL(EnumMsgCode.MSG_INVALID_PARAMS, JSON.toJSONString(ex));
    // }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponseModel<String> handlerException(HttpServletRequest request, Exception ex) {
        log.error("\npath : {}\n", request.getServletPath(), ex);
        return RestResponseModel.FAIL(EnumMsgCode.MSG_SYS_ERROR, JSON.toJSONString(ex));
    }


}
